<template>
  <div class="attendance-container">
    <!-- 部门签到表格 -->
    <el-table 
      :data="depSignDate" 
      @selection-change="onSelectionChange"
      v-loading="loading"
      stripe
      border
      style="width: 100%; margin-bottom: 20px"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="depId" label="部门" width="120">
        <template #default="{row}">
          {{ row.depId || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="clockTime" label="签到时间" width="180" />
      <el-table-column prop="clockOutTime" label="签退时间" width="180" />
      <el-table-column prop="clockRange" label="签到范围(米)" width="120">
        <template #default="{row}">
          {{ row.clockRange || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="地理位置">
        <template #default="{row}">
          {{ row.location || '获取中...' }}
        </template> 
      </el-table-column>
    </el-table>
    
    <!-- 签到按钮 -->
    <el-form-item>
      <el-button 
        :icon="Search" 
        type="primary" 
        @click="clock"
        :loading="clockLoading"
      >
        签到
      </el-button>
    </el-form-item>
    
    <!-- 考勤日历 -->
    <div class="attendance-calendar">
      <el-calendar v-model="currentMonth" @update:model-value="handleCalendarChange">
        <template #date-cell="{ data }">
          <el-tooltip
            :disabled="isFutureDate(data.date)"
            :content="getTooltipContent(data)"
            placement="top"
            popper-class="attendance-tooltip"
            raw-content
          >
            <div class="calendar-day">
              <div class="day-number">{{ data.day.split('-')[2] }}</div>
              
              <!-- 状态标签 -->
              <div 
                v-if="showStatus(data)"
                :class="['status-label', getStatusClass(data)]"
              >
                {{ getStatusText(data) }}
              </div>
            </div>
          </el-tooltip>
        </template>
      </el-calendar>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import req from '@/request'

// 表格数据
const depSignDate = ref([])
const loading = ref(false)
const clockLoading = ref(false)

const signTypeOptions = [
  { value: 1, label: '正常' },
  { value: 2, label: '未签到' },
  { value: 3, label: '未签退' },
  { value: 4, label: '异常' }
]

// 日历相关
const currentMonth = ref(new Date())
const SignList = ref([])
const holidays = ref([])

// 选择行处理
const onSelectionChange = (selection) => {
  console.log('Selected items:', selection)
}

// 获取部门签到信息
const getDep = async () => {
  loading.value = true
  try {
    const res = await req.get('/clock/getDetail')
    depSignDate.value = Array.isArray(res.data) ? res.data : [res.data]
    
    // 并行获取地理位置
    const promises = depSignDate.value.map(async record => {
      try {
        if (record.latitude && record.longitude) {
          const location = await getAddress(record.latitude, record.longitude)
          record.location = location
        } else {
          record.location = '无坐标信息'
        }
      } catch (error) {
        console.error('获取地理位置失败:', error)
        record.location = '未知地点'
      }
    })
    await Promise.all(promises)
  } catch (error) {
    console.error('获取部门签到信息失败', error)
    ElMessage.error('获取签到数据失败')
  } finally {
    loading.value = false
  }
}

// 签到功能
const clock = async () => {
  clockLoading.value = true
  try {
    const position = await new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject, {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      })
    })
    
    const clockData = {
      latitude: position.coords.latitude,
      longitude: position.coords.longitude
    }
    
    const res = await req.post('/clock/Sign', clockData)
    ElMessage.success('签到成功')
    
    await getDep()
    await getSignList()
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  } finally {
    clockLoading.value = false
  }
}

// 获取考勤记录
const getSignList = async () => {
  try {
    const params = {
      month: formatMonth(currentMonth.value)
    }
    const res = await req.get('/clockLogs/list', { params })
    SignList.value = res.data || []
  } catch (error) {
    console.error('获取考勤数据失败', error)
    ElMessage.error('获取考勤记录失败')
  }
}

// 日历相关方法
const handleCalendarChange = (val) => {
  currentMonth.value = val
  getSignList()
}

const formatMonth = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}`
}

const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const attendanceMap = computed(() => {
  return SignList.value.reduce((map, item) => {
    map[item.date] = item
    return map
  }, {})
})

const isHoliday = (date) => {
  const day = date.getDay()
  return day === 0 || day === 6
}

const isFutureDate = (date) => {
  return new Date(formatDate(date)) > new Date()
}

const showStatus = (data) => {
  const dateStr = formatDate(data.date)
  return !isFutureDate(data.date) && !isHoliday(data.date)
}

const getStatusClass = (data) => {
  const dateStr = formatDate(data.date)
  const record = attendanceMap.value[dateStr]
  
  if (!record) return 'abnormal'
  
  switch(record.status) {
    case 1: return 'normal'
    case 2: return 'no-signin'
    case 3: return 'no-signout'
    default: return 'abnormal'
  }
}

const getStatusText = (data) => {
  const dateStr = formatDate(data.date)
  const record = attendanceMap.value[dateStr]
  
  if (!record) return signTypeOptions.find(opt => opt.value === 4)?.label
  return signTypeOptions.find(opt => opt.value === record.status)?.label
}

const getTooltipContent = (data) => {
  const dateStr = formatDate(data.date)
  const record = attendanceMap.value[dateStr]
  
  if (isHoliday(data.date)) {
    return `
      <div class="holiday-tip">
        <i class="el-icon-date"></i>
        <span>节假日</span>
        <div class="holiday-desc">无考勤要求</div>
      </div>
    `
  }
  
  const statusText = record ? signTypeOptions.find(opt => opt.value === record.status)?.label : '异常'
  const signIn = record?.signInTime ? `<span class="time">${record.signInTime}</span>` : '<span class="absent">未签到</span>'
  const signOut = record?.signOutTime ? `<span class="time">${record.signOutTime}</span>` : '<span class="absent">未签退</span>'
  
  return `
    <div class="tooltip-content">
      <div class="tip-header">
        <span class="date">${dateStr}</span>
        <span class="status ${getStatusClass(data)}">${statusText}</span>
      </div>
      <div class="tip-item">
        <span class="label">签到：</span>
        ${signIn}
      </div>
      <div class="tip-item">
        <span class="label">签退：</span>
        ${signOut}
      </div>
    </div>
  `
}

// 获取地理位置
const getAddress = async (lat, lng) => {
  if (!lat || !lng) return '无坐标信息'
  
  try {
    const response = await fetch(
      `https://restapi.amap.com/v3/geocode/regeo?key=0d2cee1f7733f0cb68d49dd675ef9f43&location=${lng},${lat}`
    )
    
    const data = await response.json()
    if (data.status === '1' && data.regeocode) {
      return data.regeocode.formatted_address
    }
    return '未知地点'
  } catch (error) {
    console.error('获取地理位置失败:', error)
    return '获取位置失败'
  }
}

// 初始化数据
onMounted(() => {
  getDep()
  getSignList()
})
</script>

<style scoped>
.attendance-container {
  padding: 20px;
}

.calendar-day {
  position: relative;
  height: 100%;
  padding: 8px;
  text-align: center;
}

.day-number {
  font-size: 14px;
  margin-bottom: 4px;
}

.status-label {
  font-size: 12px;
  padding: 2px 4px;
  border-radius: 4px;
  margin-top: 2px;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 90%;
}

.status-label.normal {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-label.no-signin {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-label.no-signout {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-label.abnormal {
  background-color: #fef0f0;
  color: #f56c6c;
}

.attendance-calendar {
  margin-top: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>

<style>
.attendance-tooltip {
  background: #ffffff!important;
  border: 1px solid #ebeef5!important;
  border-radius: 8px!important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15)!important;
  padding: 12px!important;
  font-size: 13px!important;
  line-height: 1.6!important;
  max-width: 220px!important;
}

.attendance-tooltip .holiday-tip {
  text-align: center;
  color: #f56c6c;
}

.attendance-tooltip .holiday-tip i {
  font-size: 24px;
  display: block;
  margin-bottom: 6px;
}

.attendance-tooltip .holiday-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.attendance-tooltip .tip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #ebeef5;
}

.attendance-tooltip .date {
  font-weight: bold;
  color: #303133;
}

.attendance-tooltip .status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.attendance-tooltip .status.normal {
  background-color: #f0f9eb;
  color: #67c23a;
}

.attendance-tooltip .status.no-signin {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.attendance-tooltip .status.no-signout {
  background-color: #ecf5ff;
  color: #409eff;
}

.attendance-tooltip .status.abnormal {
  background-color: #fef0f0;
  color: #f56c6c;
}

.attendance-tooltip .time {
  color: #606266;
}

.attendance-tooltip .tip-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 6px 0;
}

.attendance-tooltip .label {
  color: #909399;
  margin-right: 12px;
}

.attendance-tooltip .absent {
  color: #f56c6c;
  font-weight: 500;
}
</style>